// import Store from '@/utils/store'
export default {
  /** 进行打包发版的时候注释以下代码 start */
  globalData: {
    appApiUrl: 'https://shop.hmbuy.com', // 需要调试线上的时候切换成一物家的网址 https://mob.91weimai.com
    shopId: '6000000', // 正常开发shopId:6 一物家、山几子木shopId：3869
    wxAppid: 'wx6c9bb58091a6f34c', // 正常开发小程序:wx34c2305a9c59b494 一物家: wx2f373c66dee761e6 山几子木:wx93adc6a9b2776896
    origin: 'mwx',
    appVersion: 'v2.2.0', // 本地调试使用版本号2.2.0
    isPdZb: '0',
    isJyZj: '0' // 交易组件 0 是没有开启， 1是开启了
  },
  /** 打包注释代码 end */

  /**
   * 打包小程序简单说明，请按照当前指示进行
   * 1、在打包之前确认自己需要打包分支是最新代码，保证其他的同学全部提交
   * 2、在打包的时候替换globalData全局数据
   * 3、替换build/miniprogram.config.js 中的origin，具体请去当前页面查看
   */
  /** 打包时解开此段代码，注释上方globalData 开始 start */
  // 原打包方式
  // globalData: {
  //   appApiUrl: 'APPAPIURL',
  //   shopId: 'SHOPID',
  //   wxAppid: 'WXAPPID',
  //   origin: 'mwx',
  //   appVersion: 'APPVERSION',
  //   isPdZb: 'ISPDZB',
  //   isJyZj: 'ISJYZJ'
  // },
  // 三方授权方式
  // globalData: {
  //   appApiUrl: wx.getExtConfigSync() ? wx.getExtConfigSync().appApiUrl : '',
  //   shopId: wx.getExtConfigSync() ? wx.getExtConfigSync().shopId : '',
  //   wxAppid: wx.getExtConfigSync() ? wx.getExtConfigSync().wxAppid : '',
  //   origin: 'mwx',
  //   appVersion: wx.getExtConfigSync() ? wx.getExtConfigSync().appVersion : '',
  //   isPdZb: wx.getExtConfigSync() ? wx.getExtConfigSync().isPdZb : '',
  //   isJyZj: wx.getExtConfigSync() ? wx.getExtConfigSync().isJyZj : ''
  // },
  /** 打包代码结束 end */

  /** ************************************
   * 封装好了的缓存功能
   * 参数说明：
   * key - 缓存键名
   * value - 缓存值，不提供此值时表示取得数据；提供null表示要将此缓存删除掉；提供其他非空值表示要缓存的值，会生成缓存
   * cacheTime - 要缓存多长时间，单位：秒，默认永久缓存，只有当 value 不为空值时有效
   * disableCache - 是否要强制缓存，因为我们系统是会判断是否开启调试模式的，当开启了调试模式时，一切数据都不缓存，此时为了开发调试缓存功能就需要用到此是否强制缓存
   ************************************ */
  // eslint-disable-next-line consistent-return
  wxCache(key, value, cacheTime, disableCache) {
    key = `${key}_${this.globalData.shopId}`

    var value = value !== undefined ? value : ''
    var cacheTime = cacheTime != undefined ? cacheTime : 0
    var disableCache = disableCache != undefined ? disableCache : false


    const curTime = new Date().getTime()
    if (disableCache == true) return '' // 需要关闭缓存时，传true，默认开启
    if (value == '') { // 此时为取值
      const tmp = wx.getStorageSync(key) || ''
      if (tmp == '') {
        return ''
      }
      if (tmp.etime == 0) { // 永久缓存
        return tmp.data
      }
      if (tmp.etime > curTime) { // 缓存时间大于当前时间，表示可用
        return tmp.data
      } // 缓存时间小于等于当前时间，表示已过期
      return ''
    } // 此时为设置值
    if (value == null) { // 此时表示清空值
      try {
        wx.removeStorageSync(key)
      } catch (e) {}
    } else { // 此时设置缓存
      let cacheData = {}
      let etime = 0
      if (cacheTime > 0) { // 设置了缓存时间
        etime = curTime + (cacheTime * 1000)
      }
      cacheData = {
        etime,
        data: value
      }
      wx.setStorageSync(key, cacheData)
    }
  },

  // 验证是否已经登录过
  checkLogin() {
    const globalLoginInfo = this.wxCache('global_login_info')
    // console.log('checkLogin..globalLoginInfo', globalLoginInfo)
    if (globalLoginInfo && globalLoginInfo.uid != 0) {
      return true
    }
    return false
  },

  // 上传图片
  wxUploadFile(imgLen) {
    const that = this
    function uploadFile(filepaths, callback, datalists  = []) {
      if (!filepaths.length) return
      wx.showToast({
        title: '图片上传中',
        icon: 'loading',
        // duration:3000,//这里如果不设置的话，可以用wx.hideToast来隐藏
        mask: true,
        success(res) {
          // console.log(res, 'showsuccess');
        }
      })
      wx.uploadFile({
        url: `${that.globalData.appApiUrl}/CommunityApi/uploadImg?sid=${that.globalData.shopId}`,
        filePath: filepaths.shift(),
        name: 'file',
        header: {
          'X-MAPP-ORIGIN': that.globalData.origin
        },
        formData: {},
        success(res) {
          wx.hideToast({
            success() {
              // console.log('success close');
            }
          })
          const data = res.data
          const isHttp = data.substr(0,5).indexOf('http') // 判断字符串前四位是否是http 是的话说明成功
          // console.log(isHttp,'isHttp')
          if (isHttp > -1 ) {
            datalists.push(data)
            if (filepaths.length) {
              uploadFile(filepaths, callback, datalists)
            } else {
              callback(datalists)
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data,
              showCancel: false,
              success: (res) => {

              }
            })
            // console.log('上传错误', res)
          }
        },
        fail(res) {
          wx.showModal({
            title: '提示',
            content: res.errMsg,
            showCancel: false,
            success: (res) => {

            }
          })
          // console.log('接口调用失败')
        }
      })
    }

    return new Promise((reject, resolve) => {
      imgLen = imgLen || 1
      wx.chooseImage({
        count: imgLen,
        // #ifndef MP-TOUTIAO
        sizeType: ['original', 'compressed'],
        // #endif
        sourceType: ['album', 'camera'],
        success: (res) => {
          let imgArr = [],
            fileLen = res.tempFilePaths.length
          if (fileLen > 0) {
            uploadFile(res.tempFilePaths, (datalist) => {
              reject(datalist)
            })
          }
        }
      })
    })
  },
  wxUploadMediaVideo(mediaObj = {}) {
    const that = this
    function uploadFileMedia(filepaths, callback, datalists = []) {
      if (!filepaths.length) return
      wx.uploadFile({
        url: `${that.globalData.appApiUrl}/DzHnxd/uploadVideo?sid=${that.globalData.shopId}`,
        filePath: filepaths.shift().tempFilePath,
        name: 'file',
        header: {
          'X-MAPP-ORIGIN': that.globalData.origin
        },
        formData: {},
        success(res) {
          const list = res.data.split(';')
          const data= {
            file_path: list[0],
            pic: list[1],
          }
          if (res.statusCode == 200) {
            datalists.push(data)
            if (filepaths.length) {
              uploadFile(filepaths, callback, datalists)
            } else {
              callback(datalists)
            }
          } else {
            wx.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false,
              success: (res) => {

              }
            })
          }
        },
        fail(res) {
          wx.showModal({
            title: '提示',
            content: res.errMsg,
            showCancel: false,
            success: (res) => {

            }
          })
        }
      })
    }

    return new Promise((reject, resolve) => {
      let mediaOptions = {
        count: 9,
        mediaType: ['mix'],
        sourceType: ['album', 'camera'],
        maxDuration: 10,
        sizeType: ['original', 'compressed'],
        camera: 'back',
        success: (res) => {
          let fileLen = res.tempFiles.length
          if (fileLen > 0) {
            uploadFileMedia(res.tempFiles, (datalist) => {
              reject(datalist)
            })
          }
        }
      }
      mediaOptions = Object.assign(mediaOptions, mediaObj)
      wx.chooseMedia(mediaOptions)
    })
  },


  // 上传 media
  wxUploadMedia(mediaObj={}) {
    const that = this
    function uploadFileMedia(filepaths, callback, datalists  = []) {
      if (!filepaths.length) return
      wx.uploadFile({
        url: `${that.globalData.appApiUrl}/CommunityApi/uploadImg?sid=${that.globalData.shopId}`,
        filePath: filepaths.shift().tempFilePath,
        name: 'file',
        header: {
          'X-MAPP-ORIGIN': that.globalData.origin
        },
        formData: {},
        success(res) {
          const data = res.data
          const isHttp = data.substr(0,5).indexOf('http') // 判断字符串前四位是否是http 是的话说明成功
          // console.log(isHttp,'isHttp')
          if (isHttp > -1 ) {
            datalists.push(data)
            if (filepaths.length) {
              uploadFile(filepaths, callback, datalists)
            } else {
              callback(datalists)
            }
          } else {
            wx.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false,
              success: (res) => {

              }
            })
            // console.log('上传错误', res)
          }
        },
        fail(res) {
          wx.showModal({
            title: '提示',
            content: res.errMsg,
            showCancel: false,
            success: (res) => {

            }
          })
          // console.log('接口调用失败')
        }
      })
    }

    return new Promise((reject, resolve) => {
      let mediaOptions = {
        count: 9,
        mediaType: ['mix'],
        sourceType: ['album', 'camera'],
        maxDuration: 10,
        sizeType: ['original', 'compressed'],
        camera: 'back',
        success: (res) => {
          let fileLen = res.tempFiles.length
          if (fileLen > 0) {
            uploadFileMedia(res.tempFiles, (datalist) => {
              reject(datalist)
            })
          }
        }
      }
      mediaOptions = Object.assign(mediaOptions, mediaObj)
      wx.chooseMedia(mediaOptions)
    })
  },

  // 分享参数整理转换
  HandleShareParams() {
      // 获取加载的页面栈
      let pages = getCurrentPages() || [];
      // 获取当前页面的对象
      let currentPage = pages[pages.length - 1];
      // 获取当前页面的路径
      let currentUrl = currentPage.route;
      // 获取当前url上携带的参数
      let options = currentPage.options;
      // 需要绑定上下级的参数
      let pid = 0;
      // console.log('options',options,currentPage,window.location.search)
      if (options.pid) { // 如果链接上有pid则进行赋值处理
          pid = options.pid;
      } else if (window.location.search) {
        const url = window.location.search; //获取url中"?"符后的字串
        if (typeof url === 'string') {
            let _params = {}
            if (url.indexOf("?") != -1) {
                const str = url.substr(1);
                const strs = str.split("&");
                for (let i = 0; i < strs.length; i++) {
                    _params[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]) || 0;
                }
            }
            pid = _params.pid ? _params.pid : ''
        }
      }
      // console.log('分享者pid', pid)
      // 当pid不为0的时候存储上级pid 避免用户第一次没有授权后面绑定不上上下级
      pid == 0 ? '' : this.wxCache('pid', pid)
      // 缓存当前页面链接以及参数
      this.wxCache('pathUrl', currentUrl + "?param=" + JSON.stringify(options));
  },

  // 小程序保存图片方法
  saveImage(imgUrl) {
    wx.downloadFile({
      url: imgUrl,
      success: (res) => {
        if (res.statusCode == 200) {
          let filePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: filePath,
						success: (resp) => {
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: '海报已成功保存到相册!',
                success: (res) => {
                  if (res.confirm) {
                    // console.log('点击了确定')
                  }
                }
              })
            },
            fail: (resppp) => {
              // console.log('222', resppp)
              wx.getSetting({
                success (res) {
                  // console.log('res', res)
                  if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title:'温馨提示',
                      content:'小程序将获取您相册权限保存图片',
                      showCancel: false,
                      success(res){
                        if(res.confirm){
                          // console.log('点击了确认');
                          wx.openSetting({
                            success (res) {
                              // console.log(res.authSetting)
                              res.authSetting = {
                                "scope.writePhotosAlbum": true
                              }
                            }
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        }
      },
      fail: (respp) => {
        // console.log('111', respp)
      }
    })
  },

  //批量下载图片
  saveImageQueue(urls, text) {
    let promise = Promise.resolve()
    // // console.log(promise)
    const length = urls.length
    let i = 0
    urls.forEach((url, index) => {
      promise = promise.then(() => {
        return new Promise((resolve, reject) => {
          // 根据文档 https://developers.weixin.qq.com/community/develop/doc/000ac6284f85000b140b5c03659400
          // 修正下载失败问题
          let suffix = url.substring(url.lastIndexOf('.'))
          let suffix_last = suffix.split('@')[0]
          let filename = new Date().getTime() + suffix_last
          let savePath = wx.env.USER_DATA_PATH + "/" + filename
          wx.downloadFile({
            url: url,
            filePath: savePath,
            success(res) {
              const temp = res.tempFilePath
              wx.saveImageToPhotosAlbum({
                filePath: savePath,
                success(res2) {
                  // wx.hideToast()
                  i++
                  if (i == length) {
                    if (text) {
                      wx.setClipboardData({
                        data: text,
                        success(res) {
                          wx.getClipboardData({
                            success(res) {
                              wx.showToast({
                                title: '下载成功，文字已复制',
                                icon: 'none',
                                duration: 2000
                              });
                            }
                          })
                        }
                      })
                    } else {
                      wx.showToast({
                        title: length + '张图片下载成功',
                        icon: 'none',
                        duration: 2000
                      });
                    }
                  } else {
                    wx.showToast({
                      title: '已下载' + i + '/' + length + '张图片',
                      icon: 'none'
                    });
                  }
                  resolve(res2)
                },
                fail(err) {
                  // console.log('err', temp, err)
                  wx.showToast({
                    title: '图片下载失败',
                    icon: 'none',
                    duration: 2000
                  });
                  reject(err)
                }
              })
            },
            fail(err) {
              reject(err)
            }
          })
        })
      })
    })
    return promise
  },

  // 重新获取用户信息
  wxGetUserInfo(callback){
    if(wx.getUserProfile){
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          // console.log(111,res)
          const wxUserInfo=res.userInfo;
          callback && callback(wxUserInfo);
        },
        fail: () => {
          wx.openSetting({
            success(resp) {
              // console.log(resp);
            }
          })
          return null;
        }
      })
    }else{
      wx.getUserInfo({
        success: (res) => {
          // console.log(222,res)
          const wxUserInfo=res.userInfo;
          callback && callback(wxUserInfo);
        },
        fail: () => {
          wx.openSetting({
            success(resp) {
              // console.log(resp);
            }
          })
          return null;
        }
      })
    }
  }
}
